package com.jkgl.function;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jkgl.entity.MesPersistence;
import com.jkgl.service.MesPersistenceService;
import com.jkgl.service.SendService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@RequiredArgsConstructor
@Slf4j
public class NoticeConsumerService implements StreamListener<String, ObjectRecord<String, String>> {
    private final SendService sendService;
    private final MesPersistenceService persistenceService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 不能使用多线程 -
     * because 消息逐个读取
     * @param message
     */
    @Override
    public void onMessage(ObjectRecord<String, String> message) {
//        TODO 不会对已经消费的信息进行删除 --做数据库存储以及删除
        try{

            String stream = message.getStream();
            String messageId = message.getId().toString();
            String messageBody = message.getValue();
            System.out.println(message);
            System.out.println(stream);
            System.out.println(messageId);
            System.out.println(messageBody);
            QueryWrapper<MesPersistence> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(MesPersistence::getMessageId,messageId);
            MesPersistence one = persistenceService.getOne(queryWrapper);
            boolean result=sendService.sendNoticeToUser(message);
            one.setIsSuccess(2);
            one.setIsSend(result ? 1:2);
            persistenceService.updateById(one);
            log.info("删除Notice中数据{}",message.getId());
            redisTemplate.opsForStream().delete("jkgl-notice", message.getId().toString());
        }catch (Exception e){
            e.printStackTrace();
            sendService.sendError(e,"运动提醒 定时任务部分异常 ");
        }
    }
}
